﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NewUsingDependencyInjection;
using System.Threading.Tasks;

namespace UsingDependencyInjection
{
    class Program
    {
        static async Task Main()
        {
            var p = new Program();
            //初始化EF服务容器
            p.InitializeServices();
            //添加日志到控制台
            p.ConfigureLogging();
            //通过依赖注入容器获得BooksService实例
            var service = p.Container.GetService<SecondHandBookstoreService>();
            //添加书本到数据库
            await service.AddBooksAsync();
            //读取数据库中的数据
            await service.ReadBooksAsync();
            //释放容器资源
            p.Container.Dispose();
        }
        /// <summary>
        /// 初始化依赖注入框架容器
        /// </summary>
        private void InitializeServices()
        {
            //连接字符串
            const string ConnectionString =
              @"server=(localdb)\MSSQLLocalDb;database=Books;trusted_connection=true";
            //创建ServiceCollection实例
            var services = new ServiceCollection();
            //注册瞬时实例BooksService
            services.AddTransient<SecondHandBookstoreService>()
              .AddEntityFrameworkSqlServer()//注册EF和SQLSERVER
              .AddDbContext<SecondHandBookstoreContext>(options =>
                options.UseSqlServer(ConnectionString));//添加连接字符串
            services.AddLogging();//添加日志
            //创建服务容器
            Container = services.BuildServiceProvider();
        }
        public ServiceProvider Container { get; private set; }

        private void ConfigureLogging()
        {
            ILoggerFactory loggerFactory = Container.GetService<ILoggerFactory>();
            //日志消息送入控制台
            loggerFactory.AddConsole(LogLevel.Information);
        }
    }
}
